package com.mes.biz.service.impl;

import java.math.BigDecimal;
import java.util.List;

import com.github.pagehelper.util.StringUtil;
import com.mes.biz.domain.*;
import com.mes.biz.domain.vo.ConvertRatioNumberUnit;
import com.mes.biz.service.*;
import com.mes.common.constant.BizConstants;
import com.mes.common.core.domain.BaseEntity;
import com.mes.common.core.service.BaseServiceImpl;
import com.mes.common.exception.BizException;
import com.mes.common.utils.DateUtils;
import com.mes.common.utils.SecurityUtils;
import com.mes.common.utils.StringUtils;
import com.mes.system.strategy.AutoCodeUtil;
import org.springframework.stereotype.Service;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.github.pagehelper.PageInfo;
import com.mes.biz.mapper.BizReceiveOrderMapper;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

/**
 * 领用出库单Service业务层处理
 * @author wy
 * @email wy
 * @date 2023-06-16
 */
@Service
@Transactional(readOnly = true)
public class BizReceiveOrderServiceImpl extends BaseServiceImpl<BizReceiveOrderMapper, BizReceiveOrder> implements BizReceiveOrderService {

    private static final Logger log = LoggerFactory.getLogger(BizReceiveOrderServiceImpl.class);

    @Resource
    private AutoCodeUtil autoCodeUtil;

    @Resource
    private BizReceiveOrderDetailService bizReceiveOrderDetailService;

    @Resource
    private BizProductInventoryService bizProductInventoryService;

    @Resource
    private BizProductService bizProductService;

    @Resource
    private BizProductInventoryBookService bizProductInventoryBookService;

    /**
     * 获取单条数据
     * @param bizReceiveOrder 领用出库单
     * @return 领用出库单
     */
    @Override
    public BizReceiveOrder get(BizReceiveOrder bizReceiveOrder) {
        BizReceiveOrder dto = super.get(bizReceiveOrder);
        return dto;
    }

    /**
     * 获取单条数据
     * @param id 领用出库单id
     * @return 领用出库单
     */
    @Override
    public BizReceiveOrder get(String id) {
        BizReceiveOrder dto = super.get(id);
        return dto;
    }

    /**
     * 查询领用出库单列表
     * @param bizReceiveOrder 领用出库单
     * @return 领用出库单
     */
    @Override
    public List<BizReceiveOrder> findList(BizReceiveOrder bizReceiveOrder) {
		List<BizReceiveOrder> bizReceiveOrderList = super.findList(bizReceiveOrder);
        return bizReceiveOrderList;
    }

    /**
     * 分页查询领用出库单列表
     * @param bizReceiveOrder 领用出库单
     * @return 领用出库单
     */
    @Override
    public PageInfo<BizReceiveOrder> findPage(BizReceiveOrder bizReceiveOrder) {
		PageInfo<BizReceiveOrder> page = super.findPage(bizReceiveOrder);
        return page;
    }

    /**
     * 保存领用出库单
     * @param bizReceiveOrder
     * @return 结果
     */
    @Override
    public boolean save(BizReceiveOrder bizReceiveOrder) {
        return super.save(bizReceiveOrder);
    }

    /**
     * 删除领用出库单信息
     * @param bizReceiveOrder
     * @return 结果
     */
    @Override
    public boolean remove(BizReceiveOrder bizReceiveOrder) {
        return super.remove(bizReceiveOrder);
    }

    /**
     * 批量删除领用出库单
     * @param ids 需要删除的领用出库单ID
     * @return 结果
     */
    @Transactional(readOnly = false)
    @Override
    public int deleteBizReceiveOrderByIds(String[] ids) {
        return mapper.deleteBizReceiveOrderByIds(ids, BaseEntity.DEL_FLAG_DELETE);
    }

    @Override
    @Transactional(readOnly = false)
    public Boolean insertBizReceiveOrder(BizReceiveOrder bizReceiveOrder) {
        String code = autoCodeUtil.genSerialCode("RECEIVE_ORDER_CODE",null);
        bizReceiveOrder.setReceiveCode(code);
        String tenantId = SecurityUtils.getTenantId();
        bizReceiveOrder.setTenantId(tenantId);
        bizReceiveOrder.setStatus("1");
        boolean res = save(bizReceiveOrder);
        if(res) {
            for (BizReceiveOrderDetail details : bizReceiveOrder.getDetailList()) {
                BizReceiveOrderDetail bizReceiveOrderDetail = new BizReceiveOrderDetail();
                bizReceiveOrderDetail.setProductCode(details.getProductCode());
                bizReceiveOrderDetail.setSpaceId(details.getSpaceId());
                bizReceiveOrderDetail.setUnit(details.getUnit());
                bizReceiveOrderDetail.setNumber(details.getNumber());
                bizReceiveOrderDetail.setTenantId(tenantId);
                bizReceiveOrderDetail.setRemark(details.getRemark());
                bizReceiveOrderDetail.setReceiveOrderId(bizReceiveOrder.getId());
                bizReceiveOrderDetailService.save(bizReceiveOrderDetail);

                if (StringUtil.isEmpty(details.getSpaceId())) {
                    throw new BizException("仓位不能为空!");
                }
                if (StringUtil.isEmpty(details.getUnit())) {
                    throw new BizException("单位不能为空!");
                }
                if (details.getNumber() == null) {
                    throw new BizException("数量不能为空！");
                }
                BizProduct bizProduct = bizProductService.getBizProductByProductCode(details.getProductCode());
                BizProductInventory bizProductInventory = bizProductInventoryService.getByProductIdAndSpaceId(bizProduct.getId(),
                        details.getSpaceId());
                //计算基础数量
                BigDecimal basicNumber = ConvertRatioNumberUnit.convertRatio(details.getNumber(), details.getUnit(), bizProduct);
                if (bizProductInventory == null) {
                    throw new BizException("未查询到品牌："+bizProduct.getBrand()+"，颜色："+bizProduct.getColor()+"的库存数据");
                } else {
                    BigDecimal number = bizProductInventory.getNumber() == null ? BigDecimal.ZERO : bizProductInventory.getNumber();
                    if (number != null && number.compareTo(basicNumber) >= 0) {
                    } else {
                        throw new BizException("品牌："+bizProduct.getBrand()+"，颜色："+bizProduct.getColor()+"的库存不足！");
                    }

                }
            }
        }
        return res;
    }

    @Override
    @Transactional(readOnly = false)
    public Boolean updateBizReceiveOrder(BizReceiveOrder bizReceiveOrder) {
        boolean res = save(bizReceiveOrder);
        if( bizReceiveOrder.getDetailList().size()>0) {
            String tenantId = SecurityUtils.getTenantId();
            bizReceiveOrderDetailService.deleteReceiveOrderDetailByReceiveOrderId(bizReceiveOrder.getId());
            for (BizReceiveOrderDetail details : bizReceiveOrder.getDetailList()) {
                BizReceiveOrderDetail bizReceiveOrderDetail = new BizReceiveOrderDetail();
                bizReceiveOrderDetail.setProductCode(details.getProductCode());
                bizReceiveOrderDetail.setSpaceId(details.getSpaceId());
                bizReceiveOrderDetail.setUnit(details.getUnit());
                bizReceiveOrderDetail.setNumber(details.getNumber());
                bizReceiveOrderDetail.setTenantId(tenantId);
                bizReceiveOrderDetail.setRemark(details.getRemark());
                bizReceiveOrderDetail.setReceiveOrderId(bizReceiveOrder.getId());
                bizReceiveOrderDetailService.save(bizReceiveOrderDetail);

                if (StringUtil.isEmpty(details.getSpaceId())) {
                    throw new BizException("仓位不能为空!");
                }
                if (StringUtil.isEmpty(details.getUnit())) {
                    throw new BizException("单位不能为空!");
                }
                if (details.getNumber() == null) {
                    throw new BizException("数量不能为空！");
                }
                BizProduct bizProduct = bizProductService.getBizProductByProductCode(details.getProductCode());
                BizProductInventory bizProductInventory = bizProductInventoryService.getByProductIdAndSpaceId(bizProduct.getId(),
                        details.getSpaceId());
                //计算基础数量
                BigDecimal basicNumber = ConvertRatioNumberUnit.convertRatio(details.getNumber(), details.getUnit(), bizProduct);
                if (bizProductInventory == null) {
                    throw new BizException("未查询到品牌："+bizProduct.getBrand()+"，颜色："+bizProduct.getColor()+"的库存数据");
                } else {
                    BigDecimal number = bizProductInventory.getNumber() == null ? BigDecimal.ZERO : bizProductInventory.getNumber();
                    if (number != null && number.compareTo(basicNumber) >= 0) {
                    } else {
                        throw new BizException("品牌："+bizProduct.getBrand()+"，颜色："+bizProduct.getColor()+"的库存不足！");
                    }

                }
            }
        }
        return res;
    }

    @Override
    @Transactional(readOnly = false)
    public Boolean auditBizReceiveOrder(String id) {
        BizReceiveOrder bizReceiveOrder = super.get(id);
        bizReceiveOrder.setStatus("2");
        mapper.update(bizReceiveOrder);
        //查询采购单明细信息
        BizReceiveOrderDetail paramDetail = new BizReceiveOrderDetail();
        paramDetail.setReceiveOrderId(bizReceiveOrder.getId());
        List<BizReceiveOrderDetail> list = bizReceiveOrderDetailService.findList(paramDetail);
        for(BizReceiveOrderDetail details:list) {
            if (StringUtil.isEmpty(details.getSpaceId())){
                throw new BizException("仓位不能为空!");
            }
            if (StringUtil.isEmpty(details.getUnit())){
                throw new BizException("单位不能为空!");
            }
            if (details.getNumber() == null){
                throw new BizException("数量不能为空！");
            }
            BizProduct bizProduct = bizProductService.getBizProductByProductCode(details.getProductCode());
            BizProductInventory bizProductInventory = bizProductInventoryService.getByProductIdAndSpaceId(bizProduct.getId(),
                    details.getSpaceId());
            //计算基础数量
            BigDecimal basicNumber = ConvertRatioNumberUnit.convertRatio(details.getNumber(), details.getUnit(), bizProduct);
            if(bizProductInventory==null) {
                throw new BizException("未查询到当前库存数据");
//                bizProductInventory = new BizProductInventory();
//                bizProductInventory.setProductId(bizProduct.getId());
//                bizProductInventory.setAmount(BigDecimal.ZERO);
//                bizProductInventory.setNumber(BigDecimal.ZERO.subtract(basicNumber));
//                bizProductInventory.setPrice(BigDecimal.ZERO);
//                bizProductInventory.setSpaceId(details.getSpaceId());
//                bizProductInventory.setWarehouseId(bizReceiveOrder.getWarehouseId());
//                bizProductInventory.setTenantId(SecurityUtils.getTenantId());
//                bizProductInventory.setAssistNumberA(bizProductInventory.getNumber().multiply(bizProduct.getConvertRatioA()).setScale(3,BigDecimal.ROUND_HALF_UP));
//                bizProductInventory.setAssistNumberB(bizProductInventory.getNumber().multiply(bizProduct.getConvertRatioB()).setScale(3,BigDecimal.ROUND_HALF_UP));
//                bizProductInventoryService.save(bizProductInventory);
            } else {
                BigDecimal number = bizProductInventory.getNumber() == null ? BigDecimal.ZERO : bizProductInventory.getNumber();
                if (number != null && number.compareTo(basicNumber) >= 0) {
                    bizProductInventory.setProductId(bizProduct.getId());
                    bizProductInventory.setNumber(bizProductInventory.getNumber().subtract(basicNumber));
                    bizProductInventory.setAssistNumberA(bizProductInventory.getNumber().multiply(bizProduct.getConvertRatioA()).setScale(3,BigDecimal.ROUND_HALF_UP));
                    bizProductInventory.setAssistNumberB(bizProductInventory.getNumber().multiply(bizProduct.getConvertRatioB()).setScale(3,BigDecimal.ROUND_HALF_UP));
                    bizProductInventoryService.update(bizProductInventory);
                }else {
                    throw new BizException("库存不足！");
                }

            }
            //保存产品库存台账
            BizProductInventoryBook productInventoryBook = new BizProductInventoryBook();
            productInventoryBook.setBizDate(DateUtils.getNowDate());
            productInventoryBook.setAmount(BigDecimal.ZERO);
            productInventoryBook.setAssistUnitA(bizProductInventory.getAssistUnitA());
            productInventoryBook.setAssistUnitB(bizProductInventory.getAssistUnitB());
            productInventoryBook.setSpaceId(details.getSpaceId());
            productInventoryBook.setWarehouseId(bizReceiveOrder.getWarehouseId());
            productInventoryBook.setInventoryId(bizProductInventory.getId());
            productInventoryBook.setNumber(BigDecimal.ZERO.subtract(basicNumber));
            productInventoryBook.setAssistNumberB(basicNumber.multiply(bizProduct.getConvertRatioB()).setScale(3,BigDecimal.ROUND_HALF_UP));
            productInventoryBook.setAssistNumberA(basicNumber.multiply(bizProduct.getConvertRatioA()).setScale(3,BigDecimal.ROUND_HALF_UP));
            productInventoryBook.setOrderNumber(bizReceiveOrder.getReceiveCode());
            productInventoryBook.setOrderType(BizConstants.ORDER_TYPE_RECEIVE);
            productInventoryBook.setPrice(BigDecimal.ZERO);
            productInventoryBook.setProductModel(bizProduct.getModel());
            productInventoryBook.setTenantId(SecurityUtils.getTenantId());
            productInventoryBook.setProductId(bizProduct.getId());
            productInventoryBook.setRemark(bizReceiveOrder.getRemark());
            productInventoryBook.setOrderType("5");
            bizProductInventoryBookService.save(productInventoryBook);
        }
        return true;
    }

    @Override
    @Transactional(readOnly = false)
    public Boolean doAuditBizReceiveOrder(String id) {
        BizReceiveOrder bizReceiveOrder = super.get(id);
        bizReceiveOrder.setStatus("1");
        mapper.update(bizReceiveOrder);
        BizReceiveOrderDetail paramDetail = new BizReceiveOrderDetail();
        paramDetail.setReceiveOrderId(bizReceiveOrder.getId());
        List<BizReceiveOrderDetail> list = bizReceiveOrderDetailService.findList(paramDetail);
        for(BizReceiveOrderDetail details:list) {
            BizProduct bizProduct = bizProductService.getBizProductByProductCode(details.getProductCode());
//            BizProductInventory bizProductInventory = new BizProductInventory();
//            bizProductInventory.setWarehouseId(bizReceiveOrder.getWarehouseId());
//            bizProductInventory.setSpaceId(details.getSpaceId());
//            bizProductInventory.setProductId(bizProduct.getId());
//            List<BizProductInventory> inventoryList = bizProductInventoryService.findList(bizProductInventory);

            BizProductInventory bizProductInventory = bizProductInventoryService.getByProductIdAndSpaceId(bizProduct.getId(),
                    details.getSpaceId());
            //计算基础数量
            BigDecimal basicNumber = ConvertRatioNumberUnit.convertRatio(details.getNumber(), details.getUnit(), bizProduct);
            if(bizProductInventory !=null){
                bizProductInventory.setNumber(bizProductInventory.getNumber().add(basicNumber));
                bizProductInventory.setAssistNumberA(bizProductInventory.getNumber().multiply(bizProduct.getConvertRatioA()).setScale(3,BigDecimal.ROUND_HALF_UP));
                bizProductInventory.setAssistNumberB(bizProductInventory.getNumber().multiply(bizProduct.getConvertRatioB()).setScale(3,BigDecimal.ROUND_HALF_UP));
                bizProductInventoryService.update(bizProductInventory);
            }

            //删除产品库存台账
            bizProductInventoryBookService.deleteBizProductInventoryBookByOrderNumber(bizReceiveOrder.getReceiveCode());
        }
        return true;
    }


}
